<template>
  <VPage class="app-container">
    <VTable ref="tableRef" v-bind="tableOptins" @checkboxRecords="checkboxRecords">
      <template #form="{ form }">
        <el-input
          v-model.trim="form.name"
          class="!w-[160px]"
          placeholder="币种名称"
          clearable
        ></el-input>
        <el-input
          v-model.trim="form.currency"
          class="!w-[160px]"
          placeholder="币种简称"
          clearable
        ></el-input>
        <el-select
          v-model="form.exchange_type"
          placeholder="汇率类型"
          class="!w-[160px]"
          clearable
        >
          <el-option
            v-for="item in options.exchangeRateList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-select v-model="form.status" placeholder="状态" class="!w-[160px]" clearable>
          <el-option
            v-for="item in options.statusList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </template>
      <template #toolbar_btns>
        <VButton auth="/goods/basics/currency/add" type="primary" @click="open()"
          ><svg-icon icon-class="add_new" />新增</VButton
        >
        <VButton
          auth="/goods/basics/currency/enable"
          :loading="loadings.enable"
          @click="handleStatus(1)"
        >
          <svg-icon class="mr-1" icon-class="state_finish_enable" />
          启用</VButton
        >
        <VButton
          auth="/goods/basics/currency/disable"
          :loading="loadings.disable"
          @click="handleStatus(2)"
        >
          <svg-icon class="mr-1" icon-class="state_disabled" />禁用</VButton
        >
        <VButton auth="/goods/basics/currency/delete" :loading="loadings.del" @click="del"
          ><svg-icon class="mr-1 text-red-500" icon-class="del" />删除</VButton
        >
        <VButton
          auth="/goods/basics/currency/batchImport"
          class="ml-auto"
          @click="openImport"
          >批量导入修改汇率</VButton
        >
        <VButton auth="/goods/basics/currency/batchImport" @click="handleImport"
          >批量导入平台汇率</VButton
        >
        <VButton auth="/goods/basics/currency/export" @click="handleExport">导出</VButton>
        <VButton auth="/goods/basics/currency/export" @click="handleExportTemplate"
          >财务模版导出</VButton
        >
      </template>
    </VTable>
  </VPage>
  <ComModal ref="addref" @query="query" />
  <ImportExcel ref="dialogRef" />
  <VLog ref="logRef" class="dialogPublic" :api="api.getCurrencyLog" options="id"></VLog>
  <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>
</template>
<script setup lang="jsx" name="BasicsCurrency">
import ComModal from "./components/ComModal.vue";
import ImportExcel from "./components/ImportExcel.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import VLog from "@/components/VLog";
import { getOption } from "@/api/index.js";
import api from "./api";
import DerivedCenter from "@/components/DerivedCenter";
import { downLoadExcel } from "@/utils/downloadFile";

const tableRef = ref();
const addref = ref(null);
const dialogRef = ref(null);
const records = ref([]);
let options = reactive({});
const loadings = reactive({
  enable: false,
  disable: false,
  del: false,
});

const tableOptins = reactive({
  formConfig: {
    data: {},
  },
  rowConfig: {
    height: 52,
  },
  columns: [
    { type: "checkbox", width: 50 },
    { field: "id", title: "ID", width: 100 },
    {
      field: "name",
      title: "币种名称",
    },
    { field: "currency", title: "币种简称" },
    { field: "exchange_type", title: "汇率类型" },

    {
      field: "exchange_rate",
      title: "实时汇率",
      slots: {
        header: () => {
          return (
            <div class="flex items-center">
              实时汇率
              <el-tooltip
                placement="top"
                content="<div class='text-[var(--base-color)]'>说明：</div><div class='text-[var(--base-color)] '> 1）实时汇率每天凌晨四点，同步前一天的汇率数据；</div><div class='text-[var(--base-color)]'> 2）汇率数据来源于银联，可点击跳转查询：<a class='text-[var(--base-primary-dark-bg)] hover:text-[var(--base-primary-dark-bg)]' href='https://www.unionpayintl.com/cn/rate/' target='_blank'>https://www.unionpayintl.com/cn/rate/</a></div>"
                raw-content
              >
                <svg-icon class="ml-1" icon-class="QuestionFilled" />
              </el-tooltip>
            </div>
          );
        },
        default: ({ row }) => {
          return (
            <div>
              <div class="flex items-center">实时汇率：{row.real_time_rate}</div>
              <div class="flex items-center">同步时间：{row.real_rate_date}</div>
            </div>
          );
        },
      },
    },
    { field: "exchange_rate", title: "固定汇率" },
    {
      field: "exchange_rate",
      title: "平台汇率",
      slots: {
        default: ({ row }) => {
          const ebay_rate =
            row.base_currencys_platform.find((i) => i.platform_text == "ebay")
              ?.platform_rate || "--";
          const other_rate =
            row.base_currencys_platform.find((i) => i.platform_text == "其他")
              ?.platform_rate || "--";
          return (
            <div>
              <div class="flex items-center">ebay：{ebay_rate}</div>
              <div class="flex items-center">其他：{other_rate}</div>
            </div>
          );
        },
      },
    },
    {
      field: "status_cn",
      title: "状态",
      slots: {
        default: ({ row }) => {
          return (
            <div class="flex items-center">
              {row.status == 1 ? (
                <svg-icon class="mr-1 base-text-color" icon-class="state_finish_enable" />
              ) : (
                <svg-icon class="mr-1 text-red-500" icon-class="state_finish_cover" />
              )}
              {row.status_cn}
            </div>
          );
        },
      },
      width: 95,
    },
    { field: "sort", title: "排序", width: 80 },

    { field: "update_time", title: "最后更新时间", width: 170 },
    {
      title: "操作",
      fixed: "right",
      width: 120,
      slots: {
        default: ({ row }) => {
          return (
            <div class="flex justify-start">
              {row.status == 1 || row.status == 2 ? (
                <VButton
                  auth="/goods/basics/currency/edit"
                  class="mr-4"
                  type="primary"
                  link
                  onClick={() => open(row.id)}
                >
                  编辑
                </VButton>
              ) : (
                ""
              )}
              <el-link underline={false} type="primary" onClick={() => handleLog(row.id)}>
                日志
              </el-link>
            </div>
          );
        },
      },
    },
  ],
  proxyConfig: {
    props: {
      result: "data",
      total: "total",
    },
    autoLoad: false,
    ajax: {
      query: ({ page, form }) => api.query({ ...form, ...page }),
    },
  },
});

onMounted(() => {
  fetchOption();
});
const query = () => {
  tableRef?.value.query();
};
const fetchOption = () => {
  // option不同接口判断
  getOption("currency").then((res) => {
    options = res.data;
  });
};
// 选中
const checkboxRecords = (arr) => {
  records.value = arr;
};
//获取已选中的行
const getSelectRow = () => {
  return tableRef?.value.$table.getCheckboxRecords();
};

const logRef = ref();
const handleLog = (id) => {
  logRef.value.open(id);
};
const open = (id) => {
  nextTick(() => {
    addref.value.open(id);
  });
};
const openImport = () => {
  nextTick(() => {
    const params = {
      title: "批量导入汇率",
      tempApi:
        "https://xc-goods.oss-cn-shenzhen.aliyuncs.com/goods/temple/%E6%B1%87%E7%8E%87.xlsx ",
      importApi: api.import,
    };
    dialogRef.value?.acceptParams(params);
  });
};

const handleImport = () => {
  nextTick(() => {
    const params = {
      title: "批量导入平台汇率",
      tempApi:
        "https://xc-goods.oss-cn-shenzhen.aliyuncs.com/goods/20240522/%E5%B9%B3%E5%8F%B0%E6%B1%87%E7%8E%87171637814437848.xlsx",
      importApi: api.platformImport,
    };
    dialogRef.value?.acceptParams(params);
  });
};

const isHandle = () => {
  const records = getSelectRow();
  return !records.length ? ElMessage.error("请先选择行!") && false : true;
};
const handleStatus = (status) => {
  if (!isHandle()) return;
  const records = getSelectRow().map((i) => i.id);
  status == 1 ? (loadings.enable = true) : (loadings.disable = true);
  api
    .updateStatus({ id: records, status })
    .then((res) => {
      query();
      ElMessage.success(res.message);
    })
    .finally(() => {
      status == 1 ? (loadings.enable = false) : (loadings.disable = false);
    });
};
const del = () => {
  if (!isHandle()) return;
  const records = getSelectRow().map((i) => i.id);
  ElMessageBox.confirm("此操作将永久删除该项, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    confirmButtonClass: "btnFalses",
  }).then(() => {
    loadings.del = true;
    api
      .del({ id: records, is_delete: 1 })
      .then((res) => {
        query();
        ElMessage.success(res.message);
      })
      .finally(() => {
        loadings.del = false;
      });
  });
};

const DerivedCenterRef = ref();
const handleExport = () => {
  let condition = tableRef.value.getQueryForm();
  DerivedCenterRef.value.open({
    tag_name: "goods_base_currency",
    condition,
  });
};

const handleExportTemplate = () => {
  api.exportFinance().then((res) => {
    downLoadExcel(res.data, "财务模版导出");
    ElMessage.success("操作成功");
  });
};
</script>
